package org.teremail.schema;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.teremail.common.Log;
import org.teremail.store.StoreException;
import org.teremail.util.DB;

public class Schema {

    private final static Log log = Log.getLog(Schema.class);
    
    public static void createIfNotExists(DataSource ds, Table t, Dialect dialect) {
        Connection cn = null;
        ResultSet mdrs = null;
        Statement st = null;
        try {
            cn = ds.getConnection();
            DatabaseMetaData dbmd = cn.getMetaData();
            mdrs = dbmd.getTables(null, null, dialect.getTableName(t.getName()), 
                    new String[] { "TABLE" });
            if (mdrs.next()) {
                log.info("Table exists: %s", mdrs.getString(3));
            } else {
                for (String s : t.generate(dialect)) {
                    st = cn.createStatement();
                    st.execute(s);
                }
            }
        } catch (SQLException e) {
            throw new StoreException(e);
        } finally {
            DB.close(mdrs, st, cn);
        }
    }
}
